package main

import (
	"encoding/json"
	"fmt"
	"net/url"
	"path"

	"github.com/gofiber/fiber/v2"
	log "github.com/sirupsen/logrus"
)

type Resize struct {
	Mode    string `query:"m" json:"m"` // mode: "lfit","original",
	Format  string `query:"f" json:"f"` // format: "webp","",
	Width   uint   `query:"w" json:"w"` // width
	Height  uint   `query:"h" json:"h"` // height
	Quality uint   `query:"q" json:"q"` // quality:质量0-100
}

func convert(c *fiber.Ctx) error {

	var resize Resize = Resize{
		Mode:    "original",
		Format:  "",
		Width:   0,
		Height:  0,
		Quality: uint(config.Quality), // Format=none时，质量页不生效
	}
	if err := c.QueryParser(&resize); err != nil {
		return err
	}
	query, _ := json.Marshal(resize)
	fmt.Printf("%s\n", query)
	var app = path.Clean(c.Params("app"))
	var exhaustPath = config.ExhaustPath + "/" + app
	var AppPath = config.Input[app]

	fmt.Println("app", app)

	var reqFileURI = c.Params("*")
	reqFileURI, _ = url.QueryUnescape(reqFileURI)
	reqFileURI = path.Clean(reqFileURI)

	rawImageAbs := path.Join(AppPath, reqFileURI) // /home/xxx/mypic/123.jpg
	fmt.Println("原图地址", rawImageAbs)
	// 处理原图不存在
	if !imageExists(rawImageAbs) {
		_ = c.SendStatus(404)
		return c.SendString("image not found")
	}
	if resize.Mode == "" || resize.Mode == "original" {
		// 未指定Mode发送原图
		c.Set("ETag", genEtag(rawImageAbs))
		return c.SendFile(rawImageAbs)
	}
	if !checkAllowedType(reqFileURI) {
		msg := "不支持处理的文件发送原图：" + reqFileURI
		log.Warn(msg)

		c.Set("ETag", genEtag(rawImageAbs))
		return c.SendFile(rawImageAbs)
	}

	resizeStr := fmt.Sprintf("m_%s_w_%d_h_%d_q_%d_f_%s", resize.Mode, resize.Width, resize.Height, resize.Quality, resize.Format)

	// 根据文件修改时间处理文件路径，返回值是两个，一个是webp的路径，一个是原图类型的路径，两个都可能是原图类型的路径
	outWebpFilePath := genOptimizedAbs(".webp", exhaustPath, reqFileURI, resizeStr)
	OutOriginalFilePath := genOptimizedAbs(path.Ext(rawImageAbs), exhaustPath, reqFileURI, resizeStr)

	//判断过期文件并处理
	IsFIleExpire(rawImageAbs, outWebpFilePath)
	IsFIleExpire(rawImageAbs, OutOriginalFilePath)
	// 判断浏览器是否支持webp
	Supported := guessSupportedFormat(&c.Request().Header)
	// 浏览器支持，并且指定转webp
	if Supported["webp"] && resize.Format == "webp" {
		if imageExists(outWebpFilePath) {
			var availableFiles = []string{rawImageAbs, OutOriginalFilePath, outWebpFilePath}

			c.Set("ETag", genEtag(rawImageAbs))
			return c.SendFile(findSmallestFiles(availableFiles))
		}
	} else if imageExists(OutOriginalFilePath) {
		var availableFiles = []string{rawImageAbs, OutOriginalFilePath}

		c.Set("ETag", genEtag(rawImageAbs))
		return c.SendFile(findSmallestFiles(availableFiles))
	}
	log.Info("需要压缩")
	// 压缩文件
	err := compressImage(rawImageAbs, OutOriginalFilePath, outWebpFilePath, &resize)

	if err != nil {
		// 压缩失败返回源文件
		c.Set("ETag", genEtag(rawImageAbs))
		return c.SendFile(rawImageAbs)
	}

	var availableFiles = []string{rawImageAbs, OutOriginalFilePath}
	if !Supported["webp"] {
		// 对不支持webp的浏览器发送源文件的压缩版
		c.Set("ETag", genEtag(rawImageAbs))

		var finalFile = findSmallestFiles(availableFiles)
		return c.SendFile(finalFile)
	}

	if imageExists(outWebpFilePath) && Supported["webp"] && resize.Format == "webp" {
		availableFiles = append(availableFiles, outWebpFilePath)
	}

	var finalFile = findSmallestFiles(availableFiles)
	etag := genEtag(finalFile)
	c.Set("ETag", etag)

	return c.SendFile(finalFile)

}
